<template>

	<!-- 自定义navbar组件【放在窗体外部，否则被content占据间距】 -->
	<CustomNavbar :navTitle="navTitle" :isTitleStyle="true"></CustomNavbar>

	<view class="container">
		<uni-section>
			<view class="example container">

				<uni-forms ref="valiForm" :rules="rules" :modelValue="productForm">

					<uni-forms-item label="数据ID" required name="id">
						<uni-easyinput v-model="productForm.id" disabled="" />
					</uni-forms-item>

					<uni-forms-item label="商品名称" required name="title">
						<uni-easyinput v-model="productForm.title" placeholder="请输入商品名称" />
					</uni-forms-item>
					<uni-forms-item label="单品编码" required name="sku">
						<uni-easyinput v-model="productForm.sku" placeholder="请输入单品编码" />
					</uni-forms-item>

					<uni-forms-item label="父级" name="pid">

						<uni-data-picker placeholder="请选择父级" popup-title="请选择父级" :localdata="productGategoryList"
							v-model="productForm.pid">
						</uni-data-picker>

					</uni-forms-item>
					
					<uni-forms-item label="进货价" name="purchasePrice">
						<uni-easyinput v-model="productForm.purchasePrice" placeholder="请输入商品进货价" type="digit" />
					</uni-forms-item>
					<uni-forms-item label="销售单价" name="salePrice">
						<uni-easyinput v-model="productForm.salePrice" placeholder="请输入商品销售单价" type="digit" />
					</uni-forms-item>
					<uni-forms-item label="单位" name="unit">
						<uni-easyinput v-model="productForm.unit" placeholder="请输入商品单位" />
					</uni-forms-item>

					<uni-forms-item label="状态" name="status">
						<uni-data-checkbox v-model="productForm.status" :localdata="status" />
					</uni-forms-item>

					<uni-forms-item label="商品主图" name="bigImage">

						<uni-easyinput v-model="productForm.bigImage" placeholder="请选择商品主图" />

						<view class="material-box">
							<view class="material-select">

								<view class="material-png" v-for="(item,index) in imageList" :key="index">
									
									<view class="material-sent" v-if="!item.uploadStatus">
										<progress class="select-tips" :percent="item.schedule" stroke-width="4"
											activeColor="#B99C65" />
										<view class="tips-text">
											上传进度{{item.schedule}}%
										</view>
									</view>

									<uni-icons class="close-png" type="closeempty" size="30"
										@click="closeImg(index)"></uni-icons>

									<view v-if="item.type==='image'">
										<!-- 图片 -->
										<image :src="item.tempFilePath" mode="aspectFill" class="selected-png" style="opacity: 1;"></image>
									</view>
									<view v-else class="selected-name">
										<!-- 附件 -->
										{{item.tempFilePath}}
									</view>
									
								</view>

								<view class="material-png" @click="selectPicture" v-if="selectimageIsShow">
									<uni-icons type="plus" size="30" class="u-color"></uni-icons>
									<view class="picture-text">
										选择图片
									</view>
								</view>
							</view>
						</view>

					</uni-forms-item>

					<uni-forms-item label="商品备注" name="remark">
						<uni-easyinput type="textarea" v-model="productForm.remark" placeholder="请输入商品备注" />
					</uni-forms-item>
				</uni-forms>
				<button type="primary" @click="submit('valiForm')" :disabled="isButtonDisabled" class="mt20 u-primary">提交</button>
				<button type="default" @click="handleReset('valiForm')" class="mt20">重置</button>
			</view>
		</uni-section>
	</view>
</template>

<script>
	import CustomNavbar from "@/components/CustomNavbar.vue"
	import qianTree from '@/components/Tree.vue';
	import {
		productApi
	} from '@/utils/api.js'
	export default {
		components: {
			qianTree,
			CustomNavbar
		},
		data() {
			return {
				navTitle: '',
				productGategoryList: [],
				//表单数据
				productForm: {
					id: '',
					title: '',
					sku: '',
					pid: '',
					purchasePrice: 0,
					salePrice: 0,
					unit: 0,
					status: 0,
					bigImage: '',
					remark: '',
				},
				//状态值
				status: [{
						text: '启用',
						value: 0
					},
					{
						text: '禁用',
						value: 1
					},
				],
				//校验规则
				rules: {
					title: {
						rules: [{
							required: true,
							errorMessage: '商品名称不能为空'
						}]
					},
					sku: {
						rules: [{
							required: true,
							errorMessage: '单品编码不能为空'
						}]
					},
				},
				imageList: [], //反显图片集合
				cusNo: '', //客户号
				selectimageIsShow: true, //添加图片功能按钮默认显示
				accessToken: '',
				isButtonDisabled: false, //提交按钮禁用
				hobbys: [{ //商品规格
					text: '跑步',
					value: 0
				}, {
					text: '游泳',
					value: 1
				}, {
					text: '绘画',
					value: 2
				}, {
					text: '足球',
					value: 3
				}, {
					text: '篮球',
					value: 4
				}, {
					text: '其他',
					value: 5
				}],
			}
		},
		onLoad(options) {
			this.navTitle = options.navTitle
			this.initData()
			if (options.id) {
				
				this.isButtonDisabled = true; //禁用提交
				
				uni.showToast({
					title: '正在加载数据',
					icon: 'none',
					duration: 500
				});
			
				//赋值数据【编辑】
				productApi.getProductList({
					id: options.id
				}).then(res => {
					if (res) {
						
						this.isButtonDisabled = false; //释放提交
						
						uni.showToast({
							title: '加载成功...',
							icon: 'none',
							duration: 500
						});
						
						res.data[0].pid = Number(res.data[0].pid);
						this.productForm = res.data[0];
						if (res.data[0].bigImage) {
							//赋值图片【编辑】
							this.imageList.push({
								type: 'image',
								// tempFilePath: 'http://192.168.1.7/storage/'+res.data[0].bigImage,
								tempFilePath: res.data[0].bigImage,
								schedule: 1,
								uploadStatus: true,
							})
						}
					}
				})
			}
			
			//存在商品id
			if (options.id) {
				productApi.getSpecificationsList({product_id:options.id}).then(res => {
					if (res) {
						this.productSpecificationsList = res.data;
						console.log(this.productSpecificationsList)
						
						let aaa = [];
						let bbb = [];
						for (let i of this.productSpecificationsList) {
							aaa.push({'text':i.title,'value':i.id});
							for (let j of i.children) {
								bbb.push({'text':j.title,'value':j.id});
							}
						}
						this.hobbys =  aaa;
						//过滤规格标题
						// if (options.id) {
						// 	//赋值数据【编辑】
						// 	this.filterTree(this.productSpecificationsList, options.id);
						// } else if (options.pid) { //添加子级情况
						// 	this.productSpecificationsForm.pid = Number(options.pid)
						// 	console.log(this.productSpecificationsForm)
						// }
					}
				})
			}
			
		},
		methods: {
			initData() {
				productApi.getProductGategoryList().then(res => {
					if (res) {
						this.productGategoryList = res.data;
					}
				})
			},
			//点击提交
			submit(ref) {
				this.$refs[ref].validate().then(res => {
					if (this.imageList.length) {
						this.productForm.bigImage = this.imageList[0].tempFilePath;
					}
					productApi.updateProduct(this.productForm).then(res => {
						if (res) {
							uni.showToast({
								title: res.msg,
								icon: 'success',
								duration: 500
							});
							setTimeout(function() {
								uni.navigateTo({
									url: '/pages/product/index'
								})
							}, 200)
						}
					})
				}).catch(err => {
					console.log('err', err);
				})
			},
			//选择图片
			selectPicture() {
				const that = this;
				if (this.imageList.length == 1) {
					uni.showModal({
						content: '温馨提示,最多上传1个文件'
					})
				} else {
					let counts = (1 - this.imageList.length)
					uni.chooseImage({ //chooseFile chooseImage
						count: counts,
						mediaType: ['image'],
						sourceType: ['album', 'camera'],
						success: (res) => {
							let tempFilePaths = res.tempFiles;
							console.log('选择图片', tempFilePaths)
							let selectImage = [];
							tempFilePaths.forEach((item) => {
								console.log(item)
								if (item.size >= 8388608) {
									uni.showModal({
										content: '温馨提示,单个文件大小不能超过8M'
									})
								} else {
									that.productForm.bigImage = item.path
									selectImage.push({
										type: item.type.split('/')[0],
										tempFilePath: item.path,
										schedule: 0,
										uploadStatus: false,
									})
								}
							})
							that.imageList = that.imageList.concat(selectImage);
							if (that.imageList.length == 1) {
								that.selectimageIsShow = false
							}

							that.imageList.forEach((item) => {
								if (!item.uploadStatus) {
									const uploadTask = uni.uploadFile({
										url: 'http://192.168.1.7/index.php/api.User/upload', //上传接口地址
										filePath: item.tempFilePath,
										name: 'file',
										// header: {
										// 	'content-type': 'multipart/form-data'
										// },
										formData: {
											'id': 5,
											'accessToken': that.accessToken,
										},
										success: (uploadFileRes) => {
											if (uploadFileRes.statusCode == 200) {
												let uploadDate = JSON.parse(uploadFileRes.data);
												//回显图片预览
												that.selectimageIsShow = true;
												// item.tempFilePath = 'http://192.168.1.7/storage/' + uploadDate.data
												item.tempFilePath = uploadDate.data
											}
										}
									});

									uploadTask.onProgressUpdate((res) => {
										// console.log('上传进度' + res.progress);
										// console.log('已经上传的数据长度' + res.totalBytesSent);
										// console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
										item.schedule = res.progress;
										if (res.progress == 100) {
											item.uploadStatus = true;
										}
										// // 测试条件，取消上传任务。
										// if (res.progress > 50000) {
										// 	uploadTask.abort();
										// }
									});
								}
							})
						}
					});
				}
			},
			//删除图片
			closeImg(data) {
				const that = this;
				uni.showModal({
					title: '提示',
					content: '您确定要执行此操作吗？',
					showCancel: true, //是否显示取消按钮，默认为true
					cancelText: '取消', //取消按钮的文字，默认为"取消"
					cancelColor: '#000000', //取消按钮的文字颜色，默认为"#000000"
					confirmText: '确定', //确定按钮的文字，默认为"确定"
					confirmColor: '#3CC51F', //确定按钮的文字颜色，默认为"#3CC51F"
					success: function(res) {
						if (res.confirm) {
							that.imageList.splice(data, 1)
							that.productForm.bigImage = ''
							console.log('用户点击确定');
							//执行确认后的操作
						} else if (res.cancel) {
							console.log('用户点击取消');
							//执行取消后的操作
						}
					}
				});
			},
			handleChange(e){
				console.log(e)
			}
		}
	}
</script>

<style lang="scss">
	.example {
		padding: 15px;
		background-color: #fff;
	}

	.segmented-control {
		margin-bottom: 15px;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		margin-left: 10px;
	}
</style>
<style>
	/* 附件选择器样式 */
	.material-box {
		/* width: 686rpx; */
		padding: 20rpx;
		background: #fff;
		/* margin-top: 24rpx;
		margin-left: 32rpx;
		padding-bottom: 32rpx; */
		border-radius: 8rpx;

		.item-top {
			height: 50rpx;
			line-height: 50rpx;
			font-size: 36rpx;
			font-weight: 500;
			color: #333;
		}

		.material-item {
			width: 622rpx;
			border-radius: 8rpx;
			background: #f8f8f8;
			padding: 16rpx;
			margin-top: 24rpx;
			margin-left: 24rpx;

			.item-list {
				font-size: 28rpx;
				font-weight: 400;
				line-height: 56rpx;
				height: 56rpx;
				color: #B99C65;
			}
		}

		.material-select {
			display: flex;
			flex-wrap: wrap;
			margin-bottom: 24rpx;

			.material-png {
				width: 191rpx;
				height: 191rpx;
				border-radius: 12rpx;
				border: 2rpx dashed #B99C65;
				margin-right: 20rpx;
				margin-bottom: 16rpx;
				position: relative;
				display: flex;
				align-items: center;
				justify-content: center;
				flex-direction: column;
				background: #F8F8F8;

				.material-sent {
					width: 189rpx;
					height: 189rpx;
					background: rgba(245, 245, 245, 0.5);
					position: absolute;
					display: flex;
					justify-content: center;
					align-items: center;
					flex-direction: column;

					.select-tips {
						width: 130rpx;
						height: 10rpx;
						margin-bottom: 12rpx;
					}

					.tips-text {
						font-size: 24rpx;
						color: #B99C65;
					}
				}

				.close-png {
					position: absolute;
					top: 0rpx;
					right: 20rpx;
					width: 40rpx;
					height: 40rpx;
					opacity: 0.6;
					color: red !important;
					z-index: 999;
				}

				.selected-png {
					width: 180rpx;
					height: 180rpx;
					border-radius: 12rpx;
					opacity: 1;

				}

				.selected-name {
					width: 180rpx;
					word-break: break-all;
					overflow: hidden;
				}

				.picture-png {
					width: 40rpx;
					height: 32rpx;
					margin-bottom: 8rpx;
				}

				.picture-text {
					font-size: 28rpx;
					height: 40rpx;
					line-height: 40rpx;
					color: #B99C65;
				}
			}
		}
	}
</style>